//
//  SQNewAddressViewController.m
//  pai
//
//  Created by pro on 14-11-17.
//  Copyright (c) 2014年 linjunjing. All rights reserved.
//

#import "SQNewAddressViewController.h"
#import "Global.h"

@interface SQNewAddressViewController ()

@end

@implementation SQNewAddressViewController

@synthesize areaValue=_areaValue;
@synthesize locatePicker=_locatePicker;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setTitle:@"新建收货地址"];
    
    [self.view setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    
    [self.nameLabel addTarget:self action:@selector(moveDownTextField:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.mobileLabel addTarget:self action:@selector(moveDownTextField:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.detailedLabel addTarget:self action:@selector(moveDownTextField:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    self.nameLabel.delegate = self;
    self.mobileLabel.delegate = self;
    self.detailedLabel.delegate = self;
    
    if (self.showaddress) {
        [self setAddress:self.initaddress];
    }
}
-(void)setAddress:(addr_t)address
{
    self.province = [NSString stringWithUTF8String:address.province];
    self.city = [NSString stringWithUTF8String:address.city];
    NSMutableString* addr =[NSMutableString stringWithUTF8String:address.address];
    NSArray* arr = [addr componentsSeparatedByString:@"|"];
    if(arr.count == 2){
        self.district = arr[0];
    }
    self.nameLabel.text = [NSString stringWithUTF8String:address.attn];
    self.mobileLabel.text = [NSString stringWithUTF8String:address.phone];

    self.cityLabel.text = [NSString stringWithFormat:@"%@ %@ %@",self.province,self.city,self.district];
}
-(void)moveDownTextField:(UITextField* )text
{
    [text resignFirstResponder];
    self.view.frame = CGRectMake(0, 0, 320, 568);
}
#pragma mark - UITextField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.detailedLabel) {
        self.view.frame = CGRectMake(0, -130, 320, 568);
    }
    else{
        self.view.frame = CGRectMake(0, 0, 320, 568);
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)doActionSelectCity:(id)sender {
    [self cancelLocatePicker];
    [self moveDownTextField:nil];
    self.view.frame = CGRectMake(0, -130, 320, 568);
    self.locatePicker = [[HZAreaPickerView alloc] initWithStyle:HZAreaPickerWithStateAndCityAndDistrict
                                                    withDelegate:self
                                                   andDatasource:self];
    [self.locatePicker showInView:self.view];
}

- (IBAction)doActionSubmitAddress:(id)sender {
    if ([self checkaddress]) {
        if (self.showaddress) {
            //修改
        }else{
            //添加
            add_addr_t addr;
            addr.base.msgtype = 8024;
            addr.base.len =sizeof(addr);
            addr.base.error = 0;
            
            strcpy(addr.username, [[Global instance].userinfo.username UTF8String]);
            strcpy(addr.attn, [self.nameLabel.text UTF8String]);
            strcpy(addr.phone, [self.mobileLabel.text UTF8String]);
            strcpy(addr.province, [self.province UTF8String]);
            strcpy(addr.city, [self.city UTF8String]);
            strcpy(addr.postcode, "");
            NSString* address = [NSString stringWithFormat:@"%@|%@",self.district,self.detailedLabel.text];
            strcpy(addr.addr, [address UTF8String]);
            
            NSMutableData* msgData = [NSMutableData data];
            [msgData appendBytes:&addr length:sizeof(addr)];
            
            [super sendData:msgData tag:1 withHUD:YES];
        }
    }
}
-(BOOL)checkaddress
{
    NSString* msg = @"";
    BOOL flag = YES;
    if ([self.nameLabel.text isEqualToString:@""]) {
        msg = @"请输入收件人姓名";
        flag = NO;
    }
    if ([self.mobileLabel.text isEqualToString:@""]) {
        msg = @"请输入联系电话";
        flag = NO;
    }
    if ([self.cityLabel.text isEqualToString:@""]) {
        msg = @"请选择区域";
        flag = NO;
    }
    if ([self.detailedLabel.text isEqualToString:@""]) {
        msg = @"请输入详细地址";
        flag = NO;
    }
    if (!flag) {
        UIAlertView* alterView = [[UIAlertView alloc]initWithTitle:nil message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alterView show];
    }
    
    return flag;
}
//读取数据
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    acs_base_t base;
    [data getBytes:&base length:sizeof(base)];
    if(base.error!=ACS_SUCCESS)
    {
        //出错
        [self.HUD showAnimated:YES whileExecutingBlock:^{
            self.HUD.labelText = @"添加失败";
            sleep(2);
            [self.HUD show:NO];
        } completionBlock:^{
            
        }];
    }
    else{
        [self.HUD showAnimated:YES whileExecutingBlock:^{
            self.HUD.labelText = @"添加成功";
            sleep(2);
            [self.HUD show:NO];
        } completionBlock:^{
            addr_t addresss;
            [self.delegate addAddress];
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }
}
-(void)setAreaValue:(NSString *)areaValue
{
    if (![_areaValue isEqualToString:areaValue]) {
        self.cityLabel.text = areaValue;
    }
}
#pragma mark - HZAreaPicker delegate
-(void)pickerDidChaneStatus:(HZAreaPickerView *)picker
{
    if (picker.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        self.areaValue = [NSString stringWithFormat:@"%@ %@ %@", picker.locate.state, picker.locate.city, picker.locate.district];
        
        self.province =picker.locate.state;
        self.city =picker.locate.city;
        self.district = picker.locate.district;
    }
}
-(NSArray *)areaPickerData:(HZAreaPickerView *)picker
{
    NSArray *data;
    if (picker.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        data = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"area.plist" ofType:nil]];
    }
    return data;
}
-(void)cancelLocatePicker
{
    [self.locatePicker cancelPicker];
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    self.locatePicker.delegate = nil;
    self.locatePicker = nil;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    [super touchesBegan:touches withEvent:event];
    self.view.frame = CGRectMake(0, 0, 320, 568);
    [self cancelLocatePicker];
}
@end
